<template>
  <div class="ne-upload-idea-files"
       v-loading="loading"
       element-loading-customClass="ne-loading"
       element-loading-background="rgba(255, 255, 255, 0.6)">
    <el-form
        ref="TcForm2"
        label-position="left"
        label-width="1.2rem"
        :model="Form"
        :rules="rules"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="流水号：" required>
            <el-input :disabled="true" v-model="Form.custSoNumber" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文件类型：" required prop="filetype">
            <el-select v-model="Form.filetype" placeholder="请选择">
              <el-option v-for="(item,index) in Form.filetypeOpt" :key="index" :label="item.ATTR_VALUE_NAME" :value="item.ATTR_VALUE_CODE"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关键字：">
            <el-input v-model="Form.keyword" placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传电子档案：" required prop="file">
            <el-upload
                class="clearfix"
                ref="upload"
                action=""
                :http-request="submitUpload"
                :on-change="onChange"
                :on-remove="handleRemove"
                :multiple = 'true'
                :limit="1"
                :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary" @click="selectFileFun">选取文件</el-button>
              <p class="left" style="font-size: .12rem; padding-left: .1rem;">请上传10M以下的文件！</p>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="text-center" style="margin-bottom: .15rem;">
          <el-button style="margin-left: 10px;" size="small" type="success" @click="validataFun">保存</el-button>
        </el-col>
      </el-row>
    </el-form>
    <DicTable
        height="100%"
        stripe
        highlight-current-row
        highlight-hover-row
        max-height="600"
        ref="GBLtable"
        border
        header-row-class-name="header-row-class"
        row-class-name="ne-row-class"
        :columnData="GBLtbs.tableColumns"
        :tableData="GBLtbs.tableData"
        :loading="GBLtbs.tableLoading"
        :currentPage="~~GBLtbs.tablePage.pageIndex"
        :pageSize="~~GBLtbs.tablePage.pageSize"
        :totalResult="~~GBLtbs.tablePage.rowCount"
        :pager="true"
        @on-page-change="handlePageChange"
    >
      <template #createDate="{ row }">
       <p>{{$util.dateFormat(row.createDate,"yyyy-MM-dd")}}</p>
      </template>
      <template #operation="{ row }">
        <a class="ne-a" @click="deleteFile(row)" style="color: red;">删除</a>
        <a class="ne-a" @click="downloadFile(row)" style="margin-left: .1rem;">下载</a>
      </template>
    </DicTable>
  </div>
</template>
<script>
import DicTable from "@/components/public/DicTable";
import CustOrderService from "@/api/order/CustOrderService";
import taskProInit from "@/mixins/custorder/taskProInit";
import refreshList from "@/mixins/custorder/refreshList";
import { mapState } from "vuex";
export default {
  name: 'UploadIdeaFiles',
  mixins: [taskProInit,refreshList],
  data() {
    var filetypevalida = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('文件类型不能为空！'));
      }else{
        callback();
      }
    };
    var fileListvalida = (rule, value, callback) => {
      if (!value.size) {
        return callback(new Error('请先上传文件！'));
      }
      if (value.size / 1024 / 1024 > 10) {
        return callback(new Error('上传文件大小不能超过 10MB!'));
      }else{
        callback();
      }
    };
    return {
      loading: false,
      rules: {
        filetype: [
          { validator: filetypevalida, trigger: 'change' },
          { validator: filetypevalida, trigger: 'blur' }
        ],
        file: [
          { validator: fileListvalida, trigger: 'change' },
          { validator: fileListvalida, trigger: 'blur' }
        ]
      },
      Form:{
        custSoNumber:'',
        filetype:'',
        keyword:'',
        file: {},
        filetypeOpt:[]
      },
      GBLtbs: {
        tableColumns: [
          { type: 'seq', title: '序号',width:'60'},
          { field: "fileName", title: "文件名"},
          { field: "elecFileTypeName", title: "文件类型"},
          { field: "createUserName", title: "上传人"},
          { field: "orgName", title: "上传人单位"},
          { slotName: "createDate", title: "上传时间"},
          { slotName: "operation", title: "操作",width:'120'}
        ],
        tableData:  [],
        tableLoading: false,
        tablePage: {
          pageIndex: 1,
          pageSize: 10,
          rowCount: 0,
        },
      }
    };
  },
  props: {
    CTOInfo: {
      type: [Object,Array]
    },
    ODKInfo: {
      type: [Object]
    }
  },
  computed:{
    ...mapState("user", ["user"]),
  },
  mounted() {

  },
  beforeCreate() {

  },
  created() {
    this.Form.custSoNumber = this.CTOInfos[0].custSoNumber;
    this.getDetailList();
    this.optInit();
  },
  components: {DicTable},
  methods: {
    selectFileFun(){
      this.$refs.upload.clearFiles();
      this.Form.file = {};
    },
    async downloadFile(row){

      var reqMap = {
        fileName: row.fileName,
        filePath: row.filePath,
      };

      var res = await CustOrderService.downloadElecFile(reqMap);
      if (res.size > 0) {
        let url = window.URL.createObjectURL(new Blob([res])); //创建下载链接
        let link = document.createElement("a"); //创建a标签
        link.style.display = "none"; //将a标签隐藏
        link.href = url; //给a标签添加下载链接
        link.setAttribute("download", row.fileName); // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
        document.body.appendChild(link);
        link.click(); //执行a标签
      } else {
        this.$confirm(row.fileName + "下载失败!", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warn",
          center: true,
        });
      }
    },
    async deleteFile(row){

      this.$confirm('此操作将删除此条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        let orderItemElecFiles=[{
            elecFileId: row.elecFileId,
            custId : row.custId,
            actType: "MOD",
            delFlag:"1",
            delUserId:row.delUserId,
            filePath:row.filePath
          }];
        const res = await CustOrderService.delElecFile({orderItemElecFiles:orderItemElecFiles});
        if(res.meta.resultCode=='0'){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getDetailList();
          if(this.ODKInfo.level == 'order'&&this.CTOInfos[0].elecFile=='未上传'){
            this.eventDoSearch();
          }
        }else{
          this.$message({
            showClose: true,
            message: res.meta.resultMsg,
            type: 'error'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async getDetailList(){
      this.GBLtbs.tableLoading = true;
      let {custSoNumber,custId} = this.CTOInfos[0];
      let pageInfo = {
        pageIndex:this.GBLtbs.tablePage.pageIndex,
        pageSize:this.GBLtbs.tablePage.pageSize
      }
      // const result = await CustOrderService.qryElecFileUpload({
      //   "pageInfo":{"pageIndex":1,"pageSize":12},
      //   "custSoNumber":"JT202100019703",
      //   "custId":"1"
      // });
      const result = await CustOrderService.qryElecFileUpload({custSoNumber,custId,pageInfo});
      this.GBLtbs.tableLoading = false;
      if(result.meta.resultCode=='0'){
        this.GBLtbs.tableData = result.meta.orderItemElecFiles;
        this.GBLtbs.tablePage = {
          pageIndex: ~~Number(result.meta.pageInfo.pageIndex),
          pageSize: ~~Number(result.meta.pageInfo.pageSize),
          rowCount: ~~Number(result.meta.pageInfo.rowCount)
        };
      }else{
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error'
        });
      }

    },
    onChange(file,fileList){
      this.Form.file = file;
    },
    async optInit(){
      const result = await CustOrderService.getExecuteSqlList({
        interFaceType:"ORDER",
        sqlId:"2021080202",
        paramStr:""
      });
      if(result.meta.resCode=='0'){
        this.Form.filetypeOpt = result.meta.resList.executeSqlResps;
      }else{
        this.$message({
          showClose: true,
          message: result.meta.resMsg,
          type: 'error'
        });
      }

    },
    // 上传
    validataFun(){
      this.$refs['TcForm2'].validate((valid) => {
        if (valid) {

          this.$refs.upload.submit();
        } else {

          return false;
        }
      });
    },
    delDHFun(str){
      let str2 = null
      if(str.substring(str.length-1,str.length)==","){
        str2=str.substring(0,str.length-1);
      }
      return str2;
    },
    async submitUpload(param){
      this.loading = true;
      let files = param.file,
      {custSoNumber,custId,servNbr,custOrderId} = this.CTOInfos[0],
      paramFormData = new FormData(),
      salesParam = {};
      if(this.ODKInfo.level == 'sale'){
        let orderItemIds='',
          orderItemSeqs='';
        this.CTOInfos.map((item,index)=>{
          orderItemIds+=item.orderItemId+','
          orderItemSeqs+=item.orderItemSeq+','
        });
        salesParam.orderItemIds = this.delDHFun(orderItemIds);
        salesParam.orderItemSeqs = this.delDHFun(orderItemSeqs);
      }else{
        let {custManagerId} = this.CTOInfos[0];
        salesParam = {custManagerId};
      }
      let orderItemElecFiles = {custOrderId,custSoNumber,custId,...{
          actType:'ADD',
          createUserId:this.user.staffId,
          createUserName:this.user.staffName,
          fileName:this.$refs['upload'].uploadFiles[0].name,
          fileType:this.Form.filetype,
          keyWord:this.Form.keyword,
          level:this.ODKInfo.level,
          servNbr:servNbr?servNbr:'1'
        },...salesParam};
      paramFormData.append("file", files);
      paramFormData.append("orderItemElecFiles", JSON.stringify(orderItemElecFiles));
      const uploadResult =await CustOrderService.handeldElecFileUpload( paramFormData );
      this.loading = false;
      if (uploadResult.code == 1) {
        this.$confirm(uploadResult.meta, "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "warning",
          center: true
        });
        this.progressFlag=false;
      }else if(uploadResult.code == 0){
        this.$confirm("附件:"+files.name+"上传成功", "提示", {
          confirmButtonText: "确定",
          showCancelButton: false,
          type: "success",
          center: true
        });
        this.getDetailList();
        if(this.ODKInfo.level == 'order'&&this.CTOInfos[0].elecFile=='未上传'){
          this.eventDoSearch();
        }
      }
      this.$refs.upload.clearFiles();
      this.Form.file = {};
    },
    handleRemove(file, fileList) {

    },
    handlePageChange({ currentPage, pageSize }) {
      this.GBLtbs.tablePage.pageIndex = currentPage;
      this.GBLtbs.tablePage.pageSize = pageSize;
      this.getDetailList()
    }
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-upload-list{
  float: left;
}
::v-deep .el-upload{
  float: left;
}
::v-deep .dic-table-box .ne-row-class{
  cursor: inherit;
}
.ne-a{
  color: blue;
  text-decoration: underline;
  &:hover{
   color: blue;
   text-decoration: underline;
  }
}
</style>
